package com.feisuanyz.service.impl;

import com.feisuanyz.dto.PermissionCheckQuery;
import com.feisuanyz.entity.TicketManagementDO;
import com.feisuanyz.entity.UserPermissionDO;
import com.feisuanyz.repository.TicketManagementRepository;
import com.feisuanyz.repository.UserPermissionRepository;
import com.feisuanyz.service.UserPermissionService;
import com.feisuanyz.vo.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户权限Service实现类
 */
@Slf4j
@Service
public class UserPermissionServiceImpl implements UserPermissionService {

    @Autowired
    private UserPermissionRepository userPermissionRepository;

    @Autowired
    private TicketManagementRepository ticketManagementRepository;

    @Override
    @Transactional(readOnly = true)
    public RestResult checkPermission(PermissionCheckQuery query) {
        if (query.getType() == PermissionCheckQuery.PermissionType.EVENT) {
            return checkEventPermission(query.getUserId(), query.getId());
        } else if (query.getType() == PermissionCheckQuery.PermissionType.TICKET) {
            return checkTicketPermission(query.getUserId(), query.getId());
        } else {
            log.error("未知的权限类型: {}", query.getType());
            return new RestResult("000002", "未知的权限类型");
        }
    }

    private RestResult checkEventPermission(Integer userId, Integer eventId) {
        UserPermissionDO userPermission = userPermissionRepository.findByUserIdAndEventId(userId, eventId);
        if (userPermission != null && userPermission.getPermissionLevel() != UserPermissionDO.PermissionLevel.viewer) {
            return new RestResult("000000", "调用成功");
        } else {
            return new RestResult("000001", "权限不足");
        }
    }

    private RestResult checkTicketPermission(Integer userId, Integer ticketId) {
        TicketManagementDO ticketManagement = ticketManagementRepository.findByTicketId(ticketId);
        if (ticketManagement != null) {
            UserPermissionDO userPermission = userPermissionRepository.findByUserIdAndEventId(userId, ticketManagement.getEventId());
            if (userPermission != null && userPermission.getPermissionLevel() != UserPermissionDO.PermissionLevel.viewer) {
                return new RestResult("000000", "调用成功");
            } else {
                return new RestResult("000001", "权限不足");
            }
        } else {
            return new RestResult("000001", "票务不存在");
        }
    }
}